package com.angus.auth.controller;

import com.angus.auth.form.system.LoginBody;
import com.angus.auth.form.system.RegisterBody;
import com.angus.auth.service.system.SysLoginService;
import com.angus.common.core.domain.R;
import com.angus.common.core.utils.JwtUtils;
import com.angus.common.core.utils.StringUtils;
import com.angus.common.security.auth.AuthUtil;
import com.angus.common.security.service.TokenService;
import com.angus.common.security.utils.SecurityUtils;
import com.angus.api.system.model.LoginUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 后台管理系统 token 控制
 */
@RestController
@RequestMapping("system")
public class SystemTokenController {
    @Resource
    private TokenService tokenService;

    @Resource
    private SysLoginService sysLoginService;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }



    @PostMapping("/register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
